<?php 
/**
 *  Por Federico Pisarello - SisDev Software (c) 2012 - Buenos Aires, Argentina.
 * 	fpisarello@sisdevsoft.com
 */

require("includes/funciones.inc.php");

session_start();
if(!isset($_SESSION['userName']))
	exit();

function searchABMUsers()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	require("includes/datatables_db/Datatables.php");
	
	$datatables = new Datatables();
	
	$datatables
			->select('idUser, userName, userCompleteName, userEMail')
			->from('users')
			->join('typeuser','users.idTypeUser = typeuser.idTypeUser')
			->select('description')
			->edit_column('description','$1','getDescriptionRes(description)')
			->where("users.userState <> '".$stateErase."'")
			->join('restaurant','restaurant.idRestaurant = users.idRestaurant')
			->select('businessName');
			
	if($_SESSION['userType'] != $idTypeAdministrator)
		$datatables->where("users.idTypeUser IN ($idTypeAdminResto, $idTypeYoungMan) AND users.idRestaurant = ".$_SESSION['userRestaurant']);

	return $datatables->generate();	
}

function addOrEdit()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	$mcrypt = new MCrypt();

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;

	$DB->StartTrans(); // start transaction
	
	if($_SESSION['userType'] == $idTypeAdministrator)
		$idRestaurant = $_REQUEST["cmbRestaurant"];
	else
		$idRestaurant = $_SESSION['userRestaurant'];
	
	if(!isset($_REQUEST["idUser"])){
		$strSQL = "SELECT userName FROM users WHERE userName = '".$_REQUEST["userName"]."' AND userState <> '$stateErase'";
		$rsUsers = $DB->Execute($strSQL);		

		if(!$rsUsers->EOF)
		{
			$arrJSON->status = "ERROR";
			$arrJSON->msg = $a_languages['Common.ErrorDuplicado'];
			return json_encode($arrJSON);
		}
			
		$strSQL = "INSERT INTO users ( ";
		$strSQL .= "	userName, ";
		$strSQL .= "	userPassword, ";
		$strSQL .= "	userCompleteName, ";
		$strSQL .= "	userEMail, ";
		$strSQL .= "	userPhone, ";
		$strSQL .= "	userCellPhone, ";
		$strSQL .= "	userAddress, ";
		$strSQL .= "	userState, ";
		$strSQL .= "	idRestaurant, ";
		$strSQL .= "	idTypeUser ";
		$strSQL .= "	) VALUES ( ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["userName"], "UTF-8")."', ";
		$strSQL .= "	'".$mcrypt->encrypt($_REQUEST["userPassword"])."', ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["userCompleteName"], "UTF-8")."', ";
		$strSQL .= "	'".$_REQUEST["userEMail"]."', ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["userPhone"], "UTF-8")."', ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["userCellPhone"], "UTF-8")."', ";
		$strSQL .= "	'".mb_strtoupper($_REQUEST["userAddress"], "UTF-8")."', ";
		$strSQL .= "	'".$stateAdd."', ";
		$strSQL .= "	'".$idRestaurant."', ";
		$strSQL .= "	".$_REQUEST["cmbTypeUser"];
		$strSQL .= "	)";
		
		$DB->Execute($strSQL);
		
		if($_REQUEST["cmbTypeUser"] == $idTypeYoungMan)
		{
			$insert_ID = $DB->Insert_ID();
			
			$strSQL = "SELECT * FROM tables WHERE idRestaurant = '".$idRestaurant."' AND state <> '$stateErase'";
			$rsTables = $DB->Execute($strSQL);
			
			while(!$rsTables->EOF){
				if(isset($_REQUEST['table'.$rsTables->fields('idTable')]))
				{
					$strSQL = "INSERT INTO assignedtables ( ";
					$strSQL .= "	idTable, ";
					$strSQL .= "	idUser ";
					$strSQL .= "	) VALUES ( ";
					$strSQL .= "	".$rsTables->fields('idTable').", ";
					$strSQL .= "	$insert_ID";
					$strSQL .= "	)";
					
					$DB->Execute($strSQL);
				}
				
				$rsTables->MoveNext();
			}
		}
	}
	else{
		$strSQL = "UPDATE users SET ";
		$strSQL .= "	userName = '".mb_strtoupper($_REQUEST["userName"], "UTF-8")."', ";
		if(!empty($_REQUEST["userPassword"]))
			$strSQL .= "	userPassword = '".$mcrypt->encrypt($_REQUEST["userPassword"])."', ";
		$strSQL .= "	userCompleteName = '".mb_strtoupper($_REQUEST["userCompleteName"], "UTF-8")."', ";
		$strSQL .= "	userEMail = '".$_REQUEST["userEMail"]."', ";
		$strSQL .= "	userPhone = '".mb_strtoupper($_REQUEST["userPhone"], "UTF-8")."', ";
		$strSQL .= "	userCellPhone = '".mb_strtoupper($_REQUEST["userCellPhone"], "UTF-8")."', ";
		$strSQL .= "	userAddress = '".mb_strtoupper($_REQUEST["userAddress"], "UTF-8")."', ";
		$strSQL .= "	userState = '".$stateModify."',";
		$strSQL .= "	idRestaurant = ".$idRestaurant.",";
		$strSQL .= "	idTypeUser = ".$_REQUEST["cmbTypeUser"];
		$strSQL .= " WHERE idUser = ". $_REQUEST["idUser"];
		
		$DB->Execute($strSQL);
		
		//DELETE ALL TABLES ASSIGNED
		$DB->Execute("DELETE FROM assignedtables WHERE idUser = ".$_REQUEST["idUser"]);
		
		if($_REQUEST["cmbTypeUser"] == $idTypeYoungMan)
		{
			$strSQL = "SELECT * FROM tables WHERE idRestaurant = '".$idRestaurant."' AND state <> '$stateErase'";
			$rsTables = $DB->Execute($strSQL);
			
			while(!$rsTables->EOF){
				if(isset($_REQUEST['table'.$rsTables->fields('idTable')]))
				{
					$strSQL = "INSERT INTO assignedtables ( ";
					$strSQL .= "	idTable, ";
					$strSQL .= "	idUser ";
					$strSQL .= "	) VALUES ( ";
					$strSQL .= "	".$rsTables->fields('idTable').", ";
					$strSQL .= "	".$_REQUEST['idUser'];
					$strSQL .= "	)";
					
					$DB->Execute($strSQL);
				}
				
				$rsTables->MoveNext();
			}
		}
	}
	
	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorGrabar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkGrabar'];
	}	
	return json_encode($arrJSON);
}

function del()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$DB->StartTrans(); // start transaction
	$DB->Execute("UPDATE users SET userState='$stateErase' where idUser=" . $_REQUEST["idUser"]); // execute query

	if (!$DB->CompleteTrans())
	{
		$arrJSON->status = "ERROR";
		$arrJSON->msg = $a_languages['Common.ErrorEliminar'];
	}
	else
	{
		$arrJSON->status = "OK";
		$arrJSON->msg = $a_languages['Common.OkEliminar'];
	}	
	return json_encode($arrJSON);
}

function getRestaurants()
{
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	$rsRestaurant = $DB->Execute("SELECT * FROM restaurant");
	
	$i=0;
	while(!$rsRestaurant->EOF){
		$arrRestaurant->data[$i]['idRestaurant'] = $rsRestaurant->fields(0);
		$arrRestaurant->data[$i++]['businessName'] = $rsRestaurant->fields(1);
		$rsRestaurant->MoveNext();
	}
	
	return json_encode($arrRestaurant->data);
}

function getTypeUsers()
{
	require("includes/constants.php");
	require("includes/selectLanguage.php");

	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	if($_SESSION['userType'] == $idTypeAdministrator)
		$rsTypeUsers = $DB->Execute("SELECT * FROM typeuser");
	else
		$rsTypeUsers = $DB->Execute("SELECT * FROM typeuser WHERE idTypeUser IN ($idTypeAdminResto, $idTypeYoungMan)");
	
	$i=0;
	while(!$rsTypeUsers->EOF){
		$arrTypeUsers->data[$i]['idTypeUser'] = $rsTypeUsers->fields(0);
		$arrTypeUsers->data[$i++]['description'] = $a_languages[$rsTypeUsers->fields(1)];
		$rsTypeUsers->MoveNext();
	}
	
	return json_encode($arrTypeUsers->data);
}

function getTablesRestaurant()
{
	require("includes/constants.php");
	
	try
	{	
		$DB = NewADOConnection('mysqlt');
		$DB->Connect();
		$DB->Execute("SET NAMES utf8;");
		//$DB->debug=true;
		
		if($_REQUEST["idRestaurant"]!="undefined")
			$idRestaurant = $_REQUEST["idRestaurant"];
		else
			$idRestaurant = $_SESSION['userRestaurant'];
		
		if(isset($_REQUEST["idUser"]))
		{
			$strSQL = "SELECT t.idTable, t.description, a.idAssignedTable FROM tables t".
				  	  "	LEFT JOIN assignedtables a ON t.idTable = a.idTable AND a.idUser = ".$_REQUEST["idUser"].
				  	  "	WHERE state <> '$stateErase' AND idRestaurant = $idRestaurant";
		}
		else {
			$strSQL = "SELECT idTable, description, NULL FROM tables WHERE state <> '$stateErase' AND idRestaurant = $idRestaurant";
		}
		$rsTables = $DB->Execute($strSQL);

		if(!$rsTables->EOF)
		{
			while (!$rsTables->EOF)
			{
				$arrTables->items[$i]['idTables'] = $rsTables->fields(0);
				$arrTables->items[$i]['description'] = $rsTables->fields(1);
				$arrTables->items[$i++]['selectedTable'] = $rsTables->fields(2) == NULL ? "" : "checked";
				
				$rsTables->MoveNext();
			}
			$arrTables->status = "OK";
		}
		else {
			$arrTables->status = "EMPTY";
		}
	
		return json_encode($arrTables);
	}
	catch(Exception $e)
	{
		$arrTables->status = "ERROR";
		return json_encode($arrTables);
	}
	
}

function editUser()
{
	require("includes/constants.php");
	
	$mcrypt = new MCrypt();
	
	$DB = NewADOConnection('mysqlt');
	$DB->Connect();
	$DB->Execute("SET NAMES utf8;");
	//$DB->debug=true;
	
	if($_SESSION['userType'] == $idTypeAdministrator)
		$rsUsers = $DB->Execute("SELECT * FROM users WHERE userState <> '$stateErase' AND idUser=" . $_REQUEST["idUser"]); // execute query
	else
		$rsUsers = $DB->Execute("SELECT * FROM users WHERE userState <> '$stateErase' AND idRestaurant = ".$_SESSION['userRestaurant'] ." AND idUser=" . $_REQUEST["idUser"]); // execute query
						
	if(!$rsUsers->EOF){
		$joUser->data['userName'] = $rsUsers->fields("userName");
		$joUser->data['userCompleteName'] = $rsUsers->fields("userCompleteName");
		$joUser->data['userEMail'] = $rsUsers->fields("userEMail");
		$joUser->data['userPhone'] = $rsUsers->fields("userPhone");
		$joUser->data['userAddress'] = $rsUsers->fields("userAddress");
		$joUser->data['idTypeUser'] = $rsUsers->fields("idTypeUser");
		$joUser->data['idRestaurant'] = $rsUsers->fields("idRestaurant");
		
		return json_encode($joUser->data);
	}
	else
		return json_encode('');
}

switch($_REQUEST['actionOfForm'])
{
	case "EDIT":
		echo editUser();
		break;
	case "DELETE":
		echo del();
		break;
	case "search":
		echo searchABMUsers();
		break;
	case "addOrEdit":
		echo addOrEdit();
		break;		
	case "getTypeUsers":
		echo getTypeUsers();
		break;
	case "getRestaurants":
		echo getRestaurants();
		break;
	case "getTablesRestaurant":
		echo getTablesRestaurant();
		break;
}
?>
